package com.atguigu.bean;


import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * Date:2020/9/15
 * Author:ybc
 * Description:
 */
public class Cart implements Serializable {

    //存储购物项的map集合，以图书id为键
    private Map<String, CartItem> map = new LinkedHashMap<>();

    private Integer totalCount;

    private Double totalAmount;

    public Map<String, CartItem> getMap() {
        return map;
    }

    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }

    public Integer getTotalCount() {
        totalCount = 0;
        for (CartItem cartItem : getCartItemList()) {
            totalCount += cartItem.getCount();
        }
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Double getTotalAmount() {
        BigDecimal bigDecimal1 = new BigDecimal("0.0");
        for (CartItem cartItem : getCartItemList()) {
            BigDecimal bigDecimal2 = new BigDecimal(cartItem.getAmount()+"");
            bigDecimal1 = bigDecimal1.add(bigDecimal2);
        }
        return bigDecimal1.doubleValue();
    }

    public void setTotalAmount(Double totalAmount) {
        this.totalAmount = totalAmount;
    }

    /**
     * 以list获取map中所有的购物项
     * @return
     */
    public List<CartItem> getCartItemList(){
        return new ArrayList<>(map.values());
    }

    /**
     * 向购物车中添加购物项
     */
    public void addBook2Cart(Book book){
        //先根据图书id在购物车中获取购物项信息
        CartItem cartItem = map.get(book.getId() + "");
        if(cartItem == null){
            //表示购物车中没有此图书信息，通过book对象创建购物项，并添加到map中
            cartItem = new CartItem();
            cartItem.setBook(book);
            cartItem.setCount(1);
            map.put(book.getId()+"", cartItem);
        }else{
            //表示购物车中有此图书信息，更新图书所对应的购物项的数量
            cartItem.setCount(cartItem.getCount()+1);
        }
    }

    /**
     * 删除购物车中的购物项
     */
    public void deleteCartItem(String bookId){
        map.remove(bookId);
    }

    /**
     * 清空购物车中的购物项
     */
    public void clearCart(){
        map.clear();
    }

    /**
     * 更新购物车中图书的数量
     */
    public void updateCount(String bookId, String countStr){
        CartItem cartItem = map.get(bookId);
        try {
            Integer count = Integer.parseInt(countStr);
            if(count > 0 && count <= cartItem.getBook().getStock()){
                cartItem.setCount(count);
            }
            if(count == 0){
                map.remove(bookId);
            }

        } catch (NumberFormatException e) {}
    }
}
